package com.redis;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class RedisLock {

	public static void main(String[] args) throws Exception {
		RedisLock lock = new RedisLock();
		String key = "aaaaaa";
		String lockid = lock.lock(key, 5000);
		if (lockid != null) {
			System.out.println("获得锁");
			System.out.println(lockid);
		}
		Thread.sleep(2000);
		String lockid2 = lock.lock(key, 5000);
		System.out.println(lockid2);
		lock.unlock(key, lockid2);
		System.out.println("释放锁");
		String lockid3 = lock.lock(key, 5000);
		System.out.println(lockid3);
	}

	public String lock(String key, long timeout) {
		Jedis jedis = RedisManager.getJedis();
		String value = UUID.randomUUID().toString();
		System.out.println(Thread.currentThread().getName() + "：开始枷锁");
		timeout = System.currentTimeMillis() + timeout;
		while (System.currentTimeMillis() < timeout) {
			Long flag = jedis.setnx(key, value);
			if (jedis.ttl(key) == -1) {
				jedis.expire(key, 6);
			}
			if (flag != null && flag > 0) {
				System.out.println(Thread.currentThread().getName() + ":获得锁");
				return value;
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + ": 枷锁未成功，继续尝试获取锁");
		}
		System.out.println("未获得锁");
		return null;
	}

	public boolean unlock(String key, String value) {
		Jedis jedis = RedisManager.getJedis();
		while (true) {
			jedis.watch(key);
			if (StringUtils.equals(value, jedis.get(key))) {
				Transaction transaction = jedis.multi();
				transaction.del(key);
				List<Object> list = transaction.exec();
				if (list == null) {
					continue;
				}
				return true;
			}
			jedis.unwatch();
			break;
		}
		System.out.println(Thread.currentThread().getName() + " :解锁");
		return false;

	}
}
